<template>
    <div>
        <Modal
            v-model="show"
            title="附件列表"
            width="60%"
            height="80%"
            @on-ok="confirmHandle"
        >
            <el-row>
                <el-col :span="12">
                    <el-form :model="uploadInfo" class="demo-form-inline">
                        <el-form-item label="备注:" label-width="80" style="width:90%">
                            <el-input type="textarea" resize="none" rows="6" v-model="uploadInfo.remark" placeholder="请填写备注" size="small" style="width:100%"></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="12">
                    <el-upload
                        ref="uploadRef"
                        class="upload-demo"
                        drag
                        :action="actionUrl"
                        :data="updateData"
                        :headers="headers"
                        :show-upload-list="false"
                        :before-upload="beforeUpload"
                        :on-error="uploadError"
                        :on-success="uploadSuccess"
                        :on-preview="uploadPreview"
                        multiple>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    </el-upload>
                </el-col>
            </el-row>
        </Modal>
        <span style="font-size:16px;font-weight:700;margin-right:15px;">附件列表</span>
        <el-button type="primary" size="mini"  style="margin: 0px 0 10px 0px" @click="upload">上传</el-button>
        <el-button type="primary" size="mini"  style="margin: 0px 0 0 10px" :disabled="deleteDisabled" :loading="attachmentLoading" @click="downloadList">下载</el-button>
        <el-button size="mini"  style="margin: 0px 0 0 10px" :disabled="deleteDisabled" @click="deleteList">删除</el-button>
        <el-table
            :data="pageData.list"
            border
            max-height="calc(30vh)"
            size="mini"
            :header-cell-style="{'font-weight': 300,'color': '#111'}"
            @selection-change="selectionChange"
            height="calc(30vh)">
            <el-table-column
                type="selection"
                width="50">
            </el-table-column>
            <el-table-column
                label="序号"
                type="index"
                width="50"
                align="center">
            </el-table-column>
            <el-table-column
                v-for="(item,index) in columns"
                :key="index"
                :prop="item.key"
                :label="item.title"
                :width="item.width ? item.width : ''"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <template v-if="item.type !== 'template'">
                        {{$table.tableRowFormat(scope.row, item)}}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="100">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="lookFile(scope.row)">预览</el-button>
                </template>
            </el-table-column>
        </el-table>
        <PdfViewModal ref="pdfViewModal"></PdfViewModal>
    </div>
</template>

<script>
import PdfViewModal from '@/components/pdfViewModal/pdfViewModal';
import {customerDownload} from '@/api/planInfo';
import fileDownload from "js-file-download";
import Cookies from 'js-cookie';
export default {
    name: 'attachment-model',
    components: {
        PdfViewModal
    },
    props: {
        url: {
            type: String,
            default: ''
        },
        menuActiveName: {
            type: Number,
            default: null
        },
        wmsUrl: {
            type: String,
            default: ''
        },
        selectRow: {
            type: Object,
            default() {
                return {};
            }
        }
    },
    data() {
        return {
            idx: 0,
            pageData: {
                loading: false,
                list: [],
                pageNum: 1,
                pageSize: 10,
                total: 0,
                pageOptionsList: [10, 20, 30, 40]
            },
            attachmentLoading: false,
            loading: false,
            actionUrl: '',
            updateData: {},
            headers: {
                Authorization: Cookies.get('token')
            },
            fileList: [],
            selectRows: [],
            // 附件列表展示
            show: false,
            // 上传文件
            uploadInfo: {
                remark: ''
            },
            // 附件列表项
            columns: [
                {
                    title: '文件名称',
                    key: 'fileName',
                    align: 'center',
                    type: 'text'
                },
                {
                    title: '创建时间',
                    key: 'createdDate',
                    align: 'center',
                    type: 'datetime'
                },
                {
                    title: '备注',
                    key: 'remark',
                    align: 'center',
                    type: 'text'
                }
            ]
        }
    },
    methods: {
        upload() {
            this.$emit('check-data');
            this.actionUrl = this.wmsUrl + this.url;
        },
        showUpload() {
            this.$refs.uploadRef.clearFiles();
            this.uploadInfo = {};
            this.fileList = [];
            this.show = true;
        },
        selectionChange(val) {
            this.selectRows = val;
        },
        uploadError(error, file, fileList) {
            this.$Message.error(error.returnMsg);
            this.loading = false;
        },
        uploadSuccess(response, file, fileList) {
            if (response && response.returnCode !== 200) {
                this.$Message.error(response.returnMsg);
                this.loading = false;
                return;
            } else {
                this.fileList.push(response.returnData);
                this.loading = false;
            }
        },
        uploadPreview(file) {
            this.$Message.error(file.response.returnMsg);
        },
        beforeUpload() {
            this.loading = true;
        },
        lookFile(row) {
            let suffix = row.fileName.split('.')[1].toLowerCase();
            if (suffix != 'pdf' && suffix != 'png' && suffix != 'jpg' && suffix != 'jpeg') {
                this.$message.warning('不能预览非PDF、png、jpg、jpeg格式的文件');
                return;
            }
            this.$refs.pdfViewModal.loadFile(row, this.menuActiveName);
        },
        async downloadList() {
            this.attachmentLoading = true;
            let sum = 0;
            for (const item of this.selectRows) {
                let body = {
                    "id": item.id,
                    "customerCode": null,
                    "businessNum": item.businessNum,
                    "businessType": null,
                    "fileName": item.fileName,
                    "fileUrl": item.fileUrl,
                    "remark": null,
                    "createdBy": null,
                    "createdDate": item.createdDate,
                    "lastModifiedBy": null,
                    "lastModifiedTime": null,
                    "deleteFlag": 0,
                    "fileSource": "F",
                    "businessItem": null,
                    "fileType": "null",
                    "fileTypeList": null,
                    "minioObjectName": null,
                    "displayName": item.displayName,
                    "fileSuffix": "pdf",
                    "fileSuffixEdit": "pdf",
                    "shortFileName": ''
                }
                const data = await customerDownload(body, this.wmsUrl)
                if (data.status === 200) {
                    sum++;
                    fileDownload(data.data, 'EDOC' + body.fileName.split(',')[0].toLowerCase())
                }
            }
            if (sum === this.selectRows.length) {
                this.attachmentLoading = false;
                this.$Message.success('操作成功')
            }
        },
        deleteList() {
            this.selectRows.forEach(item => {
                for (let i = 0; i < this.pageData.list.length; i++) {
                    if (this.pageData.list[i].id == item.id) {
                        this.pageData.list.splice(i, 1);
                        break;
                    }
                }
            })
            this.refreshFileList();
        },
        refreshFileList() {
            this.$emit('refresh-file-list', this.selectRow, this.pageData.list);
        },
        confirmHandle() {
            if (this.fileList.length > 0) {
                this.fileList.forEach(item => {
                    this.pageData.list.push({
                        id: --this.idx,
                        fileUrl: item.fileUrl,
                        fileName: item.fileName,
                        displayName: item.displayName,
                        remark: this.uploadInfo.remark,
                        createdDate: new Date()
                    })
                });
                this.refreshFileList();
                this.$Message.success('上传成功!');
                this.show = false;
            }
        }
    },
    created() {
    },
    watch: {
        selectRow: {
            handler(val) {
                if (val) {
                    this.pageData.list = this.selectRow && this.selectRow.fileList ? this.selectRow.fileList : [];
                }
            },
            deep: true
        }
    },
    computed: {
        deleteDisabled() {
            return this.selectRows.length == 0
        }
    }
}
</script>

<style scoped>

</style>